import { ref } from 'vue'
import { sleep } from '@/utils/utils'

export const useDelayPrint = function () {
  const printText = ref('')
  const printFinished = ref(false)
  const printStatus = ref('stop')
  let receiveQueue = []
  let isPrinting = false

  const printTextWithDelay = (text, delay = 30) => {
    return new Promise((resolve) => {
      let index = 0
      const interval = setInterval(() => {
        if (index < text.length) {
          printText.value += text[index]
          index++
        } else {
          clearInterval(interval)
          resolve()
        }
      }, delay)
    })
  }

  const startPrinting = async () => {
    let i = 0
    isPrinting = true
    printFinished.value = false
    while (true) {
      let length = receiveQueue.length
      if (length > 0) {
        await printTextWithDelay(receiveQueue.pop())
        i = 0
      } else {
        await sleep(100)
        if (i++ > 10) {
          console.log('打印结束', i)
          isPrinting = false
          printFinished.value = true
          break
        }
      }
    }
  }

  const addDelayText = function (text) {
    receiveQueue.unshift(text)
    if (!isPrinting) startPrinting()
  }

  return { printText, printFinished, addDelayText }
}
